#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "Coff.h"
#define STRING_TABLE_BUFFER_LEN 1024


char* getString( FILE *fp, Coff *c, word32 offset ){
	static char string_table_buffer[ STRING_TABLE_BUFFER_LEN ];
	char*  ro; //return object
	word32 cpos;
	word32 pos =   c->getHeader()->posSymbols 
		         + ( c->getHeader()->nSymbols * sizeof(SymbolEntry) )
				 + offset;

	cpos = ftell(fp); // backup the current position
	fseek(fp, pos, SEEK_SET);
	fread(string_table_buffer, STRING_TABLE_BUFFER_LEN, 1, fp);
	fseek(fp, cpos, SEEK_SET); // restore the old position, just in case ... 

	pos = strlen( string_table_buffer );
    ro  = (char*)malloc(pos);
	strcpy( ro, string_table_buffer );

	return string_table_buffer;
}

Symbol::Symbol(int num, Coff *c){
	word32 offset = 0;
	word32 cpos = 0;
	FILE *fp = c->getFile();

	entry = (SymbolEntry *)malloc(sizeof(SymbolEntry));
	offset = c->getHeader()->posSymbols + ( num * sizeof(SymbolEntry) );	
	cpos = ftell(fp); // backup the current position
	fseek(fp, offset, SEEK_SET);
	fread(entry, sizeof(SymbolEntry), 1, fp);
	fseek(fp, cpos, SEEK_SET); // restore the old position, just in case ...

	this->number = num;
	//string table
	if( this->entry->name.longName.zeros == 0 ){
		this->name = getString( fp, c, this->entry->name.longName.pos );

	}else{
		this->name = (char*)malloc(sizeof(this->entry->name.shortName) + 1);
		strcpy( this->name, this->entry->name.shortName );
		this->name[8] = '\0';
	}
}

Symbol::~Symbol(){
	free( entry );
	free( name );
}

